package com.efounder.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.InputType;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.efounder.adapter.AddressAdapter;
import com.efounder.adapter.CommentsAdapter;
import com.efounder.addressselector.BottomDialog;
import com.efounder.addressselector.OnAddressSelectedListener;
import com.efounder.addressselector.model.City;
import com.efounder.addressselector.model.County;
import com.efounder.addressselector.model.Province;
import com.efounder.addressselector.model.Street;
import com.efounder.bean.Address;
import com.efounder.bean.Collection;
import com.efounder.bean.CommentDatas;
import com.efounder.chat.activity.BaseActivity;
import com.efounder.chat.widget.BadgeView;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.activity.EFTransformFragmentActivity;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.frame.utils.Constants;
import com.efounder.frame.utils.EFFrameUtils;
import com.efounder.mobilemall.R;
import com.efounder.util.AbStrUtil;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.ToastUtil;
import com.efounder.utils.MallRequestUtil;
import com.efounder.utils.MyMathUtil;
import com.efounder.utils.ResStringUtil;
import com.efounder.view.AmountView;
import com.efounder.view.AniManager;
import com.efounder.view.pop.BuyNowPopuwindow;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.efounder.utils.MallRequestUtil.ADDRESS_CREATE_URL;
import static com.efounder.utils.MallRequestUtil.ADDRESS_LIST_URL;
import static com.efounder.utils.MallRequestUtil.ADDRESS_UPDATE_URL;
import static com.efounder.utils.MallRequestUtil.CART_AMOUNT_URL;
import static com.efounder.utils.MallRequestUtil.GOOD_ADDTOCART_URL;
import static com.efounder.utils.MallRequestUtil.GOOD_COLLECT_AOR;
import static com.efounder.utils.MallRequestUtil.GOOD_COMMENT_URL;

public class CommentActivity extends BaseActivity {

    RecyclerView recyclerView;
    ImageView iv_shoucang;
    TextView tv_shoucang;
    ImageView cartIcon;
    SmartRefreshLayout xRefreshView;
    LinearLayout no_comment;
    TextView tv_title;
    ImageView iv_back;

    private String TAG = this.getClass().getSimpleName();
    private RecyclerView.LayoutManager mLayoutManager;
    private CommentDatas commentDatas;
    private String goodbh;
    private int position;
    private boolean isCollection;
    private int itemNum = 1;
    private AniManager mAniManager;
    private BadgeView buyNumView;
    private int num = 0;
    private PopupWindow submitPopup, addAddressPopup, addressListPopup, editAddressPopup, confirmPopup;
    private Address defaultAddress = null;
    private Address targetAddress = null;
    private List<Address> addresses = new ArrayList<>();
    private double goodPrice;
    private int pageSize = 10;
    private List<CommentDatas.Comments> comments = new ArrayList<CommentDatas.Comments>();
    private CommentsAdapter mAdapter;
    private int count;
    private int commentCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comment);
//        StatusBarUtil.setStatusBarTranslucent(this, false);

        recyclerView = (RecyclerView) findViewById(R.id.recyclerView_comments);
        iv_shoucang = (ImageView) findViewById(R.id.iv_shoucang);
        tv_shoucang = (TextView) findViewById(R.id.tv_shoucang);
        cartIcon = (ImageView) findViewById(R.id.cart);
        xRefreshView = (SmartRefreshLayout) findViewById(R.id.xRefreshView);
        no_comment = (LinearLayout) findViewById(R.id.no_comment);
        tv_title = (TextView) findViewById(R.id.tv_title);
        iv_back = (ImageView) findViewById(R.id.iv_back);

        tv_title.setText(R.string.mail_assess);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //数据是使用Intent返回
                Intent intent = new Intent();
                //把返回数据存入Intent
                intent.putExtra("result", isCollection);
                //设置返回数据
                setResult(RESULT_OK, intent);//RESULT_OK为自定义常量
                finish();
            }
        });

        xRefreshView.setEnableLoadMore(true);
        xRefreshView.setEnableRefresh(true);
        xRefreshView.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                num += pageSize;
                getGoodsComments(String.valueOf(num), String.valueOf(pageSize));
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                comments.clear();
                num = 0;
                getGoodsComments(String.valueOf(num), String.valueOf(pageSize));
            }
        });

        goodbh = getIntent().getStringExtra("goodbh");
        commentCount = getIntent().getIntExtra("count", 0);
        position = getIntent().getIntExtra("position", 0);
        isCollection = getIntent().getBooleanExtra("isCollection", false);
        goodPrice = getIntent().getDoubleExtra("goodPrice", 0);
        LoadingDataUtilBlack.show(CommentActivity.this);
        getGoodsComments(String.valueOf(comments.size()), String.valueOf(pageSize));

        if (commentCount == 0) {
            xRefreshView.setVisibility(View.GONE);
            no_comment.setVisibility(View.VISIBLE);
        }

        if (!isCollection) {
            iv_shoucang.setImageDrawable(this.getResources().getDrawable(R.drawable.mall_favorite_unselected));
            tv_shoucang.setText(R.string.mail_collection);
            isCollection = false;
            Collection.setLove(false);
        } else {
            iv_shoucang.setImageDrawable(this.getResources().getDrawable(R.drawable.mall_favorite_selected));
            tv_shoucang.setText(R.string.mail_collectioned);
            isCollection = true;
            Collection.setLove(true);
        }
        mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mAdapter = new CommentsAdapter(this, comments, position);
        // 设置布局管理器
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setAdapter(mAdapter);

        initAnimation();
        initBadge();
    }

    private void initBadge() {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", EnvironmentVariable.getUserName());
        MallRequestUtil.getRequest(TAG, CART_AMOUNT_URL, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.has("goodTotalCount")) {
                        count = jsonObject.getInt("goodTotalCount");
                        if (count > 0) {
                            buyNumView.setText(count + "");
                            buyNumView.show();
                        }


                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(String error) {

            }
        });
    }

    public void getGoodsComments(String num, String pageSize) {
        HashMap<String, String> map = new HashMap<>();
        map.put("goodbh", goodbh);
        map.put("num", num);
        map.put("pageSize", pageSize);

        MallRequestUtil.getRequest(TAG, GOOD_COMMENT_URL, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                LoadingDataUtilBlack.dismiss();
                if (response != null && response.length() > 0) {
                    initCommentData(response);
                }
            }

            @Override
            public void onFail(String error) {
                LoadingDataUtilBlack.dismiss();
                xRefreshView.finishRefresh();
                xRefreshView.finishLoadMore();
            }
        });
    }

    private void initCommentData(String response) {
        try {
            Gson gson = new GsonBuilder().serializeNulls().create();
            commentDatas = gson.fromJson(response, CommentDatas.class);
            if (commentDatas.getResult().equals("success")) {
                for (int i = 0; i < commentDatas.getComments().size(); i++) {
                    comments.add(commentDatas.getComments().get(i));
                }
                mAdapter.notifyDataSetChanged();
            }
            xRefreshView.finishRefresh();
            xRefreshView.finishLoadMore();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void addOrRemoveCollect(final String type) {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", EnvironmentVariable.getUserName());
        map.put("goodBhs", goodbh);
        map.put("operate", type);
        MallRequestUtil.getRequest(TAG, GOOD_COLLECT_AOR, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getString("result").equals("success")) {
                        if ("add".equals(type)) {
                            iv_shoucang.setImageDrawable(getResources().getDrawable(R.drawable.mall_favorite_selected));
                            tv_shoucang.setText(R.string.mail_collectioned);
                            isCollection = true;
                            Collection.setLove(true);
                        } else if ("remove".equals(type)) {
                            iv_shoucang.setImageDrawable(getResources().getDrawable(R.drawable.mall_favorite_unselected));
                            tv_shoucang.setText(R.string.mail_collection);
                            isCollection = false;
                            Collection.setLove(false);
                        }

                    } else {
                        Toast.makeText(CommentActivity.this, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFail(String error) {
            }
        });
    }


    public void onClick(View view) {
        if (view.getId() == R.id.ll_favor) {//收藏
            if (isCollection) {//判断是否收藏
                addOrRemoveCollect("remove");
            } else {
                addOrRemoveCollect("add");
            }
        } else if (view.getId() == R.id.tv_shopcart) {//加入购物车
            addToCart(goodbh, view);
        } else if (view.getId() == R.id.tv_buy) {//立即购买
            final BuyNowPopuwindow popuwindow = new BuyNowPopuwindow(this, MyMathUtil.round3(goodPrice,2)+"");
            popuwindow.getAmountView().setOnAmountChangeListener(new AmountView.OnAmountChangeListener() {
                @Override
                public void onAmountChange(View view, int amount) {
                    itemNum = amount;
                    popuwindow.getCount().setText(String.format(getResources().getString(R.string.mail_number),999-amount+1));
                }
            });
            popuwindow.getTvConfirm().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    popuwindow.dismiss();
                    if(itemNum<=0){
                        return;
                    }
                    showSubmitPopup();
                }
            });
            popuwindow.showPopupWindow(this.findViewById(R.id.recyclerView_comments));
        } else if (view.getId() == R.id.ll_shopcart) {//购物车
            try {
                Bundle bundle = new Bundle();
                bundle.putBoolean(EFTransformFragmentActivity.EXTRA_HIDE_TITLE_BAR, true);
                EFFrameUtils.pushFragment((Class<? extends BaseFragment>) Class.forName("com.efounder.fragment.MallCartFragment"), bundle);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    public void addToCart(String goodbh, final View view) {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", EnvironmentVariable.getUserName());
        map.put("goodbh", goodbh);
        MallRequestUtil.getRequest(TAG, GOOD_ADDTOCART_URL, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    if ("success".equals(object.getString("result"))) {
                        int goodTotalCount = object.optInt("goodTotalCount");
                        startAnim(view, goodTotalCount);
                    } else {
                        Toast.makeText(CommentActivity.this, ResStringUtil.getString(R.string.mail_join_car_fail), Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(String error) {
                Toast.makeText(CommentActivity.this,  ResStringUtil.getString(R.string.mail_join_car_fail), Toast.LENGTH_LONG).show();
            }
        });
    }

    //启动动画
    public void startAnim(View v, final int totalCount) {
        int[] end_location = new int[2];
        int[] start_location = new int[2];
        v.getLocationInWindow(start_location);// 获取购买按钮的在屏幕的X、Y坐标（动画开始的坐标）
        cartIcon.getLocationInWindow(end_location);// 这是用来存储动画结束位置，也就是购物车图标的X、Y坐标
        // buyImg是动画的图片
        ImageView buyImg = new ImageView(this);
        buyImg.setImageResource(R.drawable.buy);// 设置buyImg的图片

        //        mAniManager.setTime(5500);//自定义时间
        mAniManager.setAnim(this, buyImg,cartIcon, start_location, end_location);// 开始执行动画

        mAniManager.setOnAnimListener(new AniManager.AnimListener() {
            @Override
            public void setAnimBegin(AniManager a) {
                //动画开始时的监听
            }

            @Override
            public void setAnimEnd(AniManager a) {
                //动画结束后的监听
                buyNumView.setText(totalCount + "");
                buyNumView.show();
            }
        });
    }

    private void showSubmitPopup() {
        confirmBuy();
//        View contentView;
//        LayoutInflater inflater = (LayoutInflater) this
//                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//        contentView = inflater.inflate(R.layout.layout_submit_order, null);
//        DisplayMetrics dm = getResources().getDisplayMetrics();
//        submitPopup = new PopupWindow(contentView,
//                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
//        TextView tvAddress = (TextView) contentView.findViewById(R.id.tv_address);
//        TextView tvTotalPrice = (TextView) contentView.findViewById(R.id.tv_total_price);
//        TextView tvSubmit = (TextView) contentView.findViewById(R.id.tv_submit);
//        tvTotalPrice.setText("￥" + ((goodPrice * itemNum)));
//        tvSubmit.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                HashMap<String, String> map = new HashMap<>();
//                if (targetAddress != null) {
//                    map.put("addressId", targetAddress.getAddressId());
//                } else if (defaultAddress != null) {
//                    map.put("addressId", defaultAddress.getAddressId());
//                } else if (addresses.size() > 0) {
//                    map.put("addressId", addresses.get(0).getAddressId());
//                } else {
//                    ToastUtil.showToast(CommentActivity.this, R.string.mail_fill_correct_address);
//                    return;
//                }
//                map.put("userId", EnvironmentVariable.getProperty(Constants.CHAT_USER_ID));
//                try {
//                    JSONArray jsonArray = new JSONArray();
//
//                    JSONObject jsonObject1 = new JSONObject();
//                    jsonObject1.put("goodbh", goodbh);
//                    jsonObject1.put("goodNum", itemNum);
//                    jsonObject1.put("goodPrice", goodPrice);
//                    jsonArray.put(jsonObject1);
//
//                    map.put("goods", jsonArray.toString());
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//
//                MallRequestUtil.getRequest(TAG, ORDER_CREATE_URL, map, new MallRequestUtil.MallRequestCallback() {
//                    @Override
//                    public void onSuccess(String response) {
//                        submitPopup.dismiss();
//                        ToastUtil.showToast(CommentActivity.this, R.string.mail_order_submit);
//                    }
//
//                    @Override
//                    public void onFail(String error) {
//
//                    }
//                });
//                submitPopup.dismiss();
//            }
//        });
//        if (addresses.size() > 0) {
//            if (targetAddress != null) {
//                tvAddress.setText(targetAddress.getUserName() + "，" + targetAddress.getAddress());
//            } else if (defaultAddress != null) {
//                tvAddress.setText(defaultAddress.getUserName() + "，" + defaultAddress.getAddress());
//            } else {
//                tvAddress.setText(addresses.get(0).getUserName() + "，" + addresses.get(0).getAddress());
//            }
//        }
//        tvAddress.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                if (addresses.size() > 0) {
//                    submitPopup.dismiss();
//                    showAddressListPopup();
//                } else {
//                    showAddAddressPopup();
////                submitPopup.dismiss();
//                }
//
//            }
//        });
//        submitPopup.setContentView(contentView);
//        submitPopup.setFocusable(true);
//        submitPopup.setBackgroundDrawable(new BitmapDrawable());
//        submitPopup.showAtLocation(this.findViewById(R.id.recyclerView_comments), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    /**
     * 确认购买，跳创建订单界面
     */
    private void confirmBuy() {
        Intent intent = new Intent(CommentActivity.this, CreateOrderActivity.class);
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("goodbh", goodbh);
            jsonObject.put("goodNum", itemNum + "");
            JSONArray array = new JSONArray();
            array.put(jsonObject);
            intent.putExtra("checkItems", array.toString());
            startActivity(intent);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void initAnimation() {
        //动画实例
        mAniManager = new AniManager();
        //把这个数字标签放在购物车图标上
        buyNumView = new BadgeView(this, cartIcon);
        buyNumView.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
        buyNumView.setTextColor(Color.WHITE);//数字颜色
        buyNumView.setBadgeBackgroundColor(Color.RED);//背景颜色
        buyNumView.setTextSize(9);//数字大小
    }

    private void showAddressListPopup() {
        View contentView;
        LayoutInflater inflater = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        contentView = inflater.inflate(R.layout.layout_address_list, null);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        addressListPopup = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        ImageView ivBack = (ImageView) contentView.findViewById(R.id.iv_back);
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addressListPopup.dismiss();
                showSubmitPopup();
            }
        });
        RecyclerView recyclerView = (RecyclerView) contentView.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        final AddressAdapter addressAdapter = new AddressAdapter(addresses, this);
        recyclerView.setAdapter(addressAdapter);
        addressAdapter.setOnShowAddAddressPopupListener(new AddressAdapter.OnShowAddAddressPopupListener() {
            @Override
            public void onShowAddAddressPop() {
                addressListPopup.dismiss();
                showAddAddressPopup();
            }
        });
        addressAdapter.setOnAddressSelectedListener(new AddressAdapter.OnAddressSelectedListener() {
            @Override
            public void onAddressSelected(int position) {
                for (int i = 0; i < addresses.size(); i++) {
                    if (i == position) {
                        addresses.get(i).setCurrentSelected(true);
                        targetAddress = addresses.get(i);
                    } else {
                        addresses.get(i).setCurrentSelected(false);
                    }
                }
                addressAdapter.notifyDataSetChanged();
                addressListPopup.dismiss();
                showSubmitPopup();
            }
        });
        addressAdapter.setOnShowSubmitPopupListener(new AddressAdapter.OnShowSubmitPopupListener() {
            @Override
            public void onShowSubmitPop() {

            }
        });
        addressAdapter.setOnShowEditPopupListener(new AddressAdapter.OnShowEditAddressPopupListener() {
            @Override
            public void onShowEditPop(int position) {
                addressListPopup.dismiss();
                showEditAddressPopup(position);
            }
        });
        TextView tvSave = (TextView) contentView.findViewById(R.id.tv_save_address);
        tvSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addressListPopup.dismiss();
                initAddress();
                showSubmitPopup();
            }
        });
        addressListPopup.setContentView(contentView);
        addressListPopup.setFocusable(true);
        addressListPopup.setBackgroundDrawable(new BitmapDrawable());
        addressListPopup.showAtLocation(this.findViewById(R.id.recyclerView_comments), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    public void showAddAddressPopup() {
        View contentView;
        LayoutInflater inflater = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        contentView = inflater.inflate(R.layout.layout_add_address, null);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        addAddressPopup = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        ImageView ivBack = (ImageView) contentView.findViewById(R.id.iv_back);
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addAddressPopup.dismiss();
                showSubmitPopup();
            }
        });
        final EditText etName = (EditText) contentView.findViewById(R.id.et_address_name);
        final EditText etPhone = (EditText) contentView.findViewById(R.id.et_address_phone);
        final EditText etDistrict = (EditText) contentView.findViewById(R.id.et_address_district);
        final EditText etSpecific = (EditText) contentView.findViewById(R.id.et_address_specific);
        TextView tvSave = (TextView) contentView.findViewById(R.id.tv_save_address);
        final CheckBox defaultAddressCheck = (CheckBox) contentView.findViewById(R.id.cb_default_address);
        defaultAddressCheck.setChecked(false);
        defaultAddressCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

            }
        });

        etDistrict.setInputType(InputType.TYPE_NULL);
        etDistrict.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final BottomDialog dialog = new BottomDialog(CommentActivity.this);
                dialog.setOnAddressSelectedListener(new OnAddressSelectedListener() {
                    @Override
                    public void onAddressSelected(Province province, City city, County county, Street street) {
                        etDistrict.setText(province.name + city.name + county.name);
                        dialog.dismiss();
                    }
                });
                dialog.show();
            }
        });
        tvSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (etPhone.getText().toString().equals("") || !AbStrUtil.isMobileNo(etPhone.getText().toString())) {
                    ToastUtil.showToast(CommentActivity.this, R.string.mail_enter_correct_phone_number);
                    return;
                }
                if (etName.getText().toString().equals("") || etSpecific.getText().toString().equals("")
                        || etDistrict.getText().toString().equals("")) {
                    ToastUtil.showToast(CommentActivity.this, R.string.mail_enter_complete_info);
                    return;
                }
                HashMap<String, String> map = new HashMap<>();
                map.put("userId", EnvironmentVariable.getProperty(Constants.CHAT_USER_ID));
                map.put("userName", etName.getText().toString());
                map.put("phone", etPhone.getText().toString());
                map.put("address", etSpecific.getText().toString());
                map.put("isSelected", defaultAddressCheck.isChecked() ? "1" : "0");
                map.put("area", etDistrict.getText().toString());
                MallRequestUtil.getRequest(TAG, ADDRESS_CREATE_URL, map, new MallRequestUtil.MallRequestCallback() {
                    @Override
                    public void onSuccess(String response) {
                        Log.e("MallCart", response);
                        addAddressPopup.dismiss();
                        showSubmitPopup();
                    }

                    @Override
                    public void onFail(String error) {

                    }
                });
            }
        });
        addAddressPopup.setContentView(contentView);
        addAddressPopup.setFocusable(true);
        addAddressPopup.setBackgroundDrawable(new BitmapDrawable());
        addAddressPopup.showAtLocation(this.findViewById(R.id.recyclerView_comments), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    public void showEditAddressPopup(final int position) {
        View contentView;
        LayoutInflater inflater = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        contentView = inflater.inflate(R.layout.layout_add_address, null);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        editAddressPopup = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        ImageView ivBack = (ImageView) contentView.findViewById(R.id.iv_back);
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                editAddressPopup.dismiss();
                showAddressListPopup();
            }
        });
        final EditText etName = (EditText) contentView.findViewById(R.id.et_address_name);
        etName.setHint(addresses.get(position).getUserName());
        final EditText etPhone = (EditText) contentView.findViewById(R.id.et_address_phone);
        etPhone.setHint(addresses.get(position).getPhone());
        final EditText etDistrict = (EditText) contentView.findViewById(R.id.et_address_district);
        etDistrict.setHint(addresses.get(position).getArea());
        final EditText etSpecific = (EditText) contentView.findViewById(R.id.et_address_specific);
        etSpecific.setHint(addresses.get(position).getAddress());
        TextView tvSave = (TextView) contentView.findViewById(R.id.tv_save_address);
        final CheckBox defaultAddressCheck = (CheckBox) contentView.findViewById(R.id.cb_default_address);
        final Boolean isCheck = addresses.get(position).getIsSelected().equals("1");
        defaultAddressCheck.setChecked(isCheck);
        defaultAddressCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

            }
        });
        etDistrict.setInputType(InputType.TYPE_NULL);
        etDistrict.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final BottomDialog dialog = new BottomDialog(CommentActivity.this);
                dialog.setOnAddressSelectedListener(new OnAddressSelectedListener() {
                    @Override
                    public void onAddressSelected(Province province, City city, County county, Street street) {
                        etDistrict.setText(province.name + city.name + county.name);
                        dialog.dismiss();
                    }
                });
                dialog.show();
            }
        });
        tvSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                HashMap<String, String> map = new HashMap<>();
                if (!etPhone.getText().toString().equals("")) {
                    if (!AbStrUtil.isMobileNo(etPhone.getText().toString())) {
                        ToastUtil.showToast(CommentActivity.this, R.string.mail_enter_correct_phone_number);
                        return;
                    } else {
                        addresses.get(position).setPhone(etPhone.getText().toString());
                        map.put("phone", etPhone.getText().toString());
                    }
                } else {
                    map.put("phone", addresses.get(position).getPhone());
                }
                if (!etName.getText().toString().equals("")) {
                    addresses.get(position).setUserName(etName.getText().toString());
                    map.put("userName", etName.getText().toString());
                } else {
                    map.put("userName", addresses.get(position).getUserName());
                }
                if (!etSpecific.getText().toString().equals("")) {
                    addresses.get(position).setAddress(etSpecific.getText().toString());
                    map.put("address", etSpecific.getText().toString());
                } else {
                    map.put("address", addresses.get(position).getAddress());
                }
                if (!etDistrict.getText().toString().equals("")) {
                    addresses.get(position).setArea(etDistrict.getText().toString());
                    map.put("area", etDistrict.getText().toString());
                } else {
                    map.put("area", addresses.get(position).getArea());
                }
                addresses.get(position).setIsSelected(defaultAddressCheck.isChecked() ? "1" : "0");
                map.put("addressId", addresses.get(position).getAddressId());
                map.put("userId", EnvironmentVariable.getProperty(Constants.CHAT_USER_ID));
                map.put("isSelected", defaultAddressCheck.isChecked() ? "1" : "0");

                MallRequestUtil.getRequest(TAG, ADDRESS_UPDATE_URL, map, new MallRequestUtil.MallRequestCallback() {
                    @Override
                    public void onSuccess(String response) {
                        Log.e("MallCart", response);
                        editAddressPopup.dismiss();
                        initAddress();
                        showAddressListPopup();
                    }

                    @Override
                    public void onFail(String error) {

                    }
                });
            }
        });
        editAddressPopup.setContentView(contentView);
        editAddressPopup.setFocusable(true);
        editAddressPopup.setBackgroundDrawable(new BitmapDrawable());
        editAddressPopup.showAtLocation(this.findViewById(R.id.recyclerView_comments), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    public void initAddress() {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", EnvironmentVariable.getProperty(Constants.CHAT_USER_ID));
        MallRequestUtil.getRequest(TAG, ADDRESS_LIST_URL, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    JSONArray jsonArray = jsonObject.getJSONArray("addresses");
                    if (jsonArray.length() > 0) {
                        addresses.clear();
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject addressObject = jsonArray.getJSONObject(i);
                            Address address = new Address();
                            address.setAddressId(addressObject.getString("addressid"));
                            address.setAddress(addressObject.getString("address"));
                            address.setArea(addressObject.getString("area"));
                            address.setIsSelected(addressObject.getString("isselected"));
                            address.setUserName(addressObject.getString("username"));
                            address.setPhone(addressObject.getString("phone"));
                            if (address.getIsSelected().equals("1")) {
                                defaultAddress = address;
                            }
                            addresses.add(address);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFail(String error) {

            }
        });
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //数据是使用Intent返回
            Intent intent = new Intent();
            //把返回数据存入Intent
            intent.putExtra("result", isCollection);
            //设置返回数据
            setResult(RESULT_OK, intent);//RESULT_OK为自定义常量
            //关闭Activity
            finish();
        }
        return super.onKeyDown(keyCode, event);

    }
}
